import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { formatDateTime } from '@/utils'
import type { Price, PriceQuery, PriceForm, BindDeviceForm, PriceStats, PriceHistory } from '@/types/price'

// 导出价格管理相关的响应式数据和函数
export const usePriceManagement = () => {
  const loading = ref(false)
  const submitting = ref(false)
  const priceDialogVisible = ref(false)
  const bindDialogVisible = ref(false)
  const historyDialogVisible = ref(false)
  const isEdit = ref(false)
  const currentPrice = ref<Price | null>(null)
  const selectedRows = ref<Price[]>([])
  const priceFormRef = ref<FormInstance>()

  // 搜索表单
  const searchForm = reactive<PriceQuery>({
    keyword: '',
    wasteType: undefined,
    status: undefined,
    dateRange: [],
    page: 1,
    size: 20
  })

  // 分页信息
  const pagination = reactive({
    page: 1,
    size: 20,
    total: 0
  })

  // 价格统计
  const priceStats = reactive<PriceStats>({
    activePrices: 156,
    totalDevices: 289,
    averagePrice: 0.68,
    priceTrend: '+3.2%'
  })

  // 价格列表
  const priceList = ref<Price[]>([])

  // 设备选项
  const deviceOptions = ref<any[]>([])

  // 价格表单
  const priceForm = reactive<PriceForm>({
    wasteType: 'paper',
    price: 0.6,
    unit: 'kg',
    deviceIds: [],
    effectiveDate: '',
    expiredDate: '',
    remark: ''
  })

  // 绑定表单
  const bindForm = reactive<BindDeviceForm>({
    priceId: 0,
    deviceIds: []
  })

  // 价格历史列表
  const priceHistoryList = ref<PriceHistory[]>([])

  // 设备传输数据
  const deviceTransferData = computed(() => {
    return deviceOptions.value.map(device => ({
      key: device.id,
      label: `${device.name} (${device.code}) - ${device.location}`
    }))
  })

  // 回收类型选项
  const wasteTypeOptions = [
    { label: '纸壳类', value: 'paper' },
    { label: '织物类', value: 'textile' },
    { label: '混合类', value: 'mixed' }
  ]

  // 表单验证规则
  const priceRules: FormRules = {
    wasteType: [
      { required: true, message: '请选择回收类型', trigger: 'change' }
    ],
    price: [
      { required: true, message: '请输入价格', trigger: 'blur' },
      { type: 'number', min: 0.01, max: 100, message: '价格范围在 0.01 到 100 元', trigger: 'blur' }
    ],
    unit: [
      { required: true, message: '请选择单位', trigger: 'change' }
    ],
    effectiveDate: [
      { required: false, message: '请选择生效时间', trigger: 'change' }
    ]
  }

  // 获取回收类型标签
  const getWasteTypeTag = (wasteType: string) => {
    switch (wasteType) {
      case 'paper':
        return 'primary'
      case 'textile':
        return 'danger'
      case 'mixed':
        return ''
      default:
        return 'info'
    }
  }

  // 获取回收类型文本
  const getWasteTypeText = (wasteType: string) => {
    switch (wasteType) {
      case 'paper':
        return '纸壳类'
      case 'textile':
        return '织物类'
      case 'mixed':
        return '混合类'
      default:
        return '未知类型'
    }
  }

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'active':
        return 'success'
      case 'inactive':
        return 'warning'
      case 'expired':
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'active':
        return '生效中'
      case 'inactive':
        return '未生效'
      case 'expired':
        return '已过期'
      default:
        return '未知状态'
    }
  }

  // 加载价格列表
  const loadPriceList = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      // 演示数据
      priceList.value = [
        {
          id: 1,
          wasteType: 'paper',
          price: 0.6,
          unit: 'kg',
          deviceIds: [1, 2, 3],
          deviceNames: ['智能回收箱001', '智能回收箱002', '智能回收箱003'],
          status: 'active',
          effectiveDate: '2024-01-01 00:00:00',
          expiredDate: '2024-12-31 23:59:59',
          remark: '纸壳类回收价格',
          createdAt: '2024-01-01 10:00:00',
          updatedAt: '2024-01-01 10:00:00'
        },
        {
          id: 2,
          wasteType: 'textile',
          price: 0.4,
          unit: 'kg',
          deviceIds: [4, 5],
          deviceNames: ['智能回收箱004', '智能回收箱005'],
          status: 'active',
          effectiveDate: '2024-01-01 00:00:00',
          remark: '织物类回收价格',
          createdAt: '2024-01-01 10:00:00',
          updatedAt: '2024-01-01 10:00:00'
        },
        {
          id: 3,
          wasteType: 'mixed',
          price: 0.5,
          unit: 'kg',
          deviceIds: [6, 7],
          deviceNames: ['智能回收箱006', '智能回收箱007'],
          status: 'active',
          effectiveDate: '2024-01-01 00:00:00',
          remark: '混合类回收价格',
          createdAt: '2024-01-01 10:00:00',
          updatedAt: '2024-01-01 10:00:00'
        }
      ]

      pagination.total = priceList.value.length
    } catch (error) {
      ElMessage.error('加载价格列表失败')
    } finally {
      loading.value = false
    }
  }

  // 加载设备列表
  const loadDeviceList = async () => {
    try {
      // 模拟设备数据
      deviceOptions.value = [
        { id: 1, name: '智能回收箱001', code: 'DL001', location: 'A区1号楼' },
        { id: 2, name: '智能回收箱002', code: 'DL002', location: 'A区2号楼' },
        { id: 3, name: '智能回收箱003', code: 'DL003', location: 'B区1号楼' },
        { id: 4, name: '智能回收箱004', code: 'DL004', location: 'B区2号楼' },
        { id: 5, name: '智能回收箱005', code: 'DL005', location: 'C区1号楼' },
        { id: 6, name: '智能回收箱006', code: 'DL006', location: 'C区2号楼' },
        { id: 7, name: '智能回收箱007', code: 'DL007', location: 'D区1号楼' }
      ]
    } catch (error) {
      ElMessage.error('加载设备列表失败')
    }
  }

  // 搜索处理
  const handleSearch = () => {
    pagination.page = 1
    loadPriceList()
  }

  // 重置处理
  const handleReset = () => {
    Object.assign(searchForm, {
      keyword: '',
      wasteType: undefined,
      status: undefined,
      dateRange: []
    })
    pagination.page = 1
    loadPriceList()
  }

  // 分页处理
  const handlePageChange = (page: number) => {
    pagination.page = page
    loadPriceList()
  }

  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.page = 1
    loadPriceList()
  }

  // 选择处理
  const handleSelectionChange = (selection: Price[]) => {
    selectedRows.value = selection
  }

  // 新建价格
  const handleCreatePrice = () => {
    isEdit.value = false
    Object.assign(priceForm, {
      wasteType: 'paper',
      price: 0.6,
      unit: 'kg',
      deviceIds: [],
      effectiveDate: '',
      expiredDate: '',
      remark: ''
    })
    priceDialogVisible.value = true
  }

  // 编辑价格
  const handleEditPrice = (row: Price) => {
    isEdit.value = true
    currentPrice.value = row
    Object.assign(priceForm, {
      wasteType: row.wasteType,
      price: row.price,
      unit: row.unit,
      deviceIds: row.deviceIds,
      effectiveDate: row.effectiveDate,
      expiredDate: row.expiredDate,
      remark: row.remark
    })
    priceDialogVisible.value = true
  }

  // 绑定设备
  const handleBindDevice = (row: Price) => {
    currentPrice.value = row
    bindForm.priceId = row.id
    bindForm.deviceIds = [...row.deviceIds]
    bindDialogVisible.value = true
  }

  // 价格提交
  const handlePriceSubmit = async () => {
    if (!priceFormRef.value) return

    try {
      await priceFormRef.value.validate()
      submitting.value = true

      if (isEdit.value) {
        // 调用编辑价格API
        ElMessage.success('价格修改成功')
      } else {
        // 调用新建价格API
        ElMessage.success('价格创建成功')
      }

      priceDialogVisible.value = false
      loadPriceList()
    } catch (error) {
      ElMessage.error('操作失败')
    } finally {
      submitting.value = false
    }
  }

  // 绑定提交
  const handleBindSubmit = async () => {
    try {
      // 调用绑定设备API
      ElMessage.success('设备绑定成功')
      bindDialogVisible.value = false
      loadPriceList()
    } catch (error) {
      ElMessage.error('绑定失败')
    }
  }

  // 批量绑定
  const handleBatchBind = () => {
    ElMessage.info('批量绑定功能开发中...')
  }

  // 批量停用
  const handleBatchDisable = async () => {
    try {
      await ElMessageBox.confirm(
        `确定要停用选中的 ${selectedRows.value.length} 个价格规则吗？`,
        '批量停用',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      // 调用批量停用API
      ElMessage.success('批量停用成功')
      loadPriceList()
    } catch (error) {
      // 用户取消
    }
  }

  // 导出价格
  const handleExport = () => {
    ElMessage.info('导出价格功能开发中...')
  }

  // 价格历史
  const handlePriceHistory = () => {
    // 模拟价格历史数据
    priceHistoryList.value = [
      {
        id: 1,
        priceId: 1,
        oldPrice: 0.5,
        newPrice: 0.6,
        operator: '管理员',
        reason: '市场价格调整',
        createdAt: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        priceId: 2,
        oldPrice: 0.7,
        newPrice: 0.8,
        operator: '管理员',
        reason: '塑料回收成本上涨',
        createdAt: '2024-01-01 10:00:00'
      }
    ]
    historyDialogVisible.value = true
  }

  // 更多操作
  const handleMoreAction = (command: string, row: Price) => {
    switch (command) {
      case 'view-history':
        currentPrice.value = row
        handlePriceHistory()
        break
      case 'copy-price':
        ElMessage.info('复制价格功能开发中...')
        break
      case 'disable':
        handleToggleStatus(row)
        break
      case 'delete':
        handleDeletePrice(row)
        break
    }
  }

  // 切换状态
  const handleToggleStatus = async (row: Price) => {
    try {
      const action = row.status === 'active' ? '停用' : '启用'
      await ElMessageBox.confirm(
        `确定要${action}这个价格规则吗？`,
        `${action}价格`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      // 调用切换状态API
      ElMessage.success(`${action}成功`)
      loadPriceList()
    } catch (error) {
      // 用户取消
    }
  }

  // 删除价格
  const handleDeletePrice = async (row: Price) => {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个价格规则吗？',
        '删除价格',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      // 调用删除价格API
      ElMessage.success('删除成功')
      loadPriceList()
    } catch (error) {
      // 用户取消
    }
  }

  return {
    loading,
    submitting,
    priceDialogVisible,
    bindDialogVisible,
    historyDialogVisible,
    isEdit,
    currentPrice,
    selectedRows,
    priceFormRef,
    searchForm,
    pagination,
    priceStats,
    priceList,
    deviceOptions,
    priceForm,
    bindForm,
    priceHistoryList,
    deviceTransferData,
    priceRules,
    getWasteTypeTag,
    getWasteTypeText,
    getStatusTag,
    getStatusText,
    loadPriceList,
    loadDeviceList,
    handleSearch,
    handleReset,
    handlePageChange,
    handleSizeChange,
    handleSelectionChange,
    handleCreatePrice,
    handleEditPrice,
    handleBindDevice,
    handlePriceSubmit,
    handleBindSubmit,
    handleBatchBind,
    handleBatchDisable,
    handleExport,
    handlePriceHistory,
    handleMoreAction,
    handleToggleStatus,
    handleDeletePrice
  }
}
